<?php
namespace Base\Service;

use Base\Util\Files;

use Admin\Auth\Adapter;

use Zend\Stdlib\Hydrator\ClassMethods;
use Doctrine\ORM\EntityManager;

/**
 * @class AbstractService
 * 
 * @package Base\Service
 * @author Diego
 *
 */
abstract class AbstractService {
	
	/**
	 * @var Doctrine\ORM\EntityManager
	 */
	protected $em;
	
	/**
	 * @var Base\Entity\AbstractEntity
	 */
	protected $entity;
	
	/**
	 * @var string
	 */
	protected $imagesPath;
	
	
	/**
	 * Dependency Injection
	 * @param EntityManager $em
	 */
	public function __construct( EntityManager $em ) {
		$this->em = $em;
	}
	
	
	/**
	 * @method save()
	 * Método da classe abstrata para inserido ou alteração de entidades
	 * @param array $data
	 * @return AbstractEntity $entity
	 */
	public function save( array $data ) {
		
		if ( $data['id'] ) {
			
			$entity = $this->em->getReference( $this->entity, $data['id'] );
			//(new Hydrator\ClassMethods())->hydrate( $data, $entity ); PHP 5.4 somente
			$hydrator = new ClassMethods();
			$hydrator->hydrate( $data, $entity );
			
		} else {

			$entity = new $this->entity( $data );
		}
		
		$this->em->persist( $entity );
		$this->em->flush();
		
		// renomeia a pasta de imagens
		$this->renameImageFolder($entity);
		
		return $entity;
	}
		
	
	
	
	/**
	 * @method delete()
	 * Método da classe abstrata para excluir entidades
	 * @param int $id
	 * @return int $id
	 */
	public function remove( $id ) {
	
		$entity = $this->em->find( $this->entity, $id );
		
		if( isset ( $entity ) ) {
			$this->em->remove( $entity );
			$this->em->flush();
			
			// remove as imagens
			$dir = $this->imagesPath . $id;
			
			if( is_dir($dir) ){
			
				$files = new Files();
				$files->removeDirectory($dir);
			
			}
			
			return $id;
		}
	}
	
	
	
	/**
	 *
	 * @param unknown $entity
	 */
	protected function renameImageFolder( $entity ) {
	
		// renomeia a pasta de imagens para o caminho definitivo
		$adapter = new Adapter();
		$imageFolder = 'new_' . $adapter->getUserId();
	
		// verifica se a pasta existe
		if(is_dir($this->imagesPath . $imageFolder)){
			// renomeia a pasta de imagens
			rename($this->imagesPath . $imageFolder, $this->imagesPath . $entity->getId());
		}
	
	}
}

?>